package com.npr.config;

import com.npr.MyFilter.LoginTicketFilter;
import com.npr.controller.interceptor.LoginTicketInterceptor;
import com.npr.service.UserService;
import com.npr.util.CommunityConstant;
import com.npr.util.CommunityUtil;
import com.npr.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Autowired
    UserService userService;
    @Autowired
    HostHolder hostHolder;
    @Autowired
    private LoginTicketFilter loginTicketFilter;

    @Override
    public void configure(WebSecurity web) throws Exception {
        //忽略静态资源的拦截
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/*",
                        "/letter/**",
                        "/notice/**",
                        "like",
                        "/follow",
                        "/unfollow"

                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR,
                        AUTHORITY_USER
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete",
                        "/data/**",
                        "actuator/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .antMatchers(
                        "/data/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll()
                .and().csrf().disable();//不启用csrf
        //权限不够时的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //没有登录的处理
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");//判断返回的是什么
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            //说明请求是异步请求，返回的是json
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"你还没有登录哦"));
                        }else {
                            //不是异步请求，就直接重定向到登录页面
                            response.sendRedirect(request.getContextPath()+"/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //权限不足的处理
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");//判断返回的是什么
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            //说明请求是异步请求，返回的是json
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"你还没有访问此功能的权限"));
                        }else {
                            //不是异步请求，就重定向到权限不足页面
                            response.sendRedirect(request.getContextPath()+"/denied");
                        }
                    }
                });
        // Security底层默认会拦截/logout请求，进行退出处理
        //覆盖它的逻辑，才能执行自己的退出请求
        //编一个不存在的请求，为了欺骗security，使其拦截这个不存在的请求，这样我们自己的退出请求就不被拦截了
        http.logout().logoutUrl("/securitylogout");
       /* http.addFilterBefore(new Filter() {
            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                (HttpServletRequest)servletRequest.getCookies();

            }
        });*/
        http.addFilterBefore(loginTicketFilter, HeaderWriterFilter.class);
    }
}
